package com.pinc.akb48;

import java.lang.reflect.Field;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.VideoView;

public class VideoActivity extends WebviewActivity {
	private myChromeClient wvChromeClient;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview_layout);

		initWidget();
		wvChromeClient = new myChromeClient();
		wv.setWebChromeClient(wvChromeClient);
		wv.loadUrl(String.format("http://m.youtube.com/#/results?q=%s&orderby=published", getResources().getString(R.string.str_keyword)));
	}

	@Override
	protected void initWidget() {
		super.initWidget();

		tv_title.setText(getResources().getString(R.string.str_video));
	}

	public class myChromeClient extends WebChromeClient implements
	OnCompletionListener {
		private CustomViewCallback mCallback;
		private VideoView mCustomVideoView;
		private FrameLayout mCustomViewContainer;

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress >= 100)
				ll_progress.setVisibility(View.INVISIBLE);
			else
				ll_progress.setVisibility(View.VISIBLE);
			pgb.setProgress(newProgress);
		}

		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			mCallback = callback;
			// super.onShowCustomView(view, callback);
			if (view instanceof FrameLayout) {
				mCustomViewContainer = (FrameLayout) view;
				if (mCustomViewContainer.getFocusedChild() instanceof VideoView) {
					mCustomVideoView = (VideoView) mCustomViewContainer
					.getFocusedChild();
					Uri mUri = null;
					try {
						Field mUriField = VideoView.class
						.getDeclaredField("mUri");
						mUriField.setAccessible(true);
						mUri = (Uri) mUriField.get(mCustomVideoView);
					} catch (Exception e) {
					}
					mCustomVideoView.setOnCompletionListener(this);
					Intent intent = new Intent(VideoActivity.this,
							VideoPlayer.class);
					intent.putExtra("url", mUri.toString());
					VideoActivity.this.startActivity(intent);
				}
			}
		}

		public void complete() {
			if (mCustomVideoView == null)
				return;
			mCustomVideoView.stopPlayback();
			mCustomVideoView = null;
			mCallback.onCustomViewHidden();
		}

		@Override
		public void onCompletion(MediaPlayer mp) {
			mp.stop();
			mCallback.onCustomViewHidden();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		wvChromeClient.complete();
	}
}
